<template>
	<view>
		<!-- 搜索部分 -->
		<view class="search-box">
			<uni-search-bar bgColor="#fff" radius="50" placeholder="请输入搜索内容"  @input="inputHandler" />
		</view>
		<!-- 商品列表部分 -->
		<view class="history-box">
			<view class="search-history">
				<text>搜索历史</text>
				<uni-icons type="trash" size="16" @click="cleanHistory"></uni-icons>
			</view>
			<view class="history-list" v-if="searchList.length===0">
				<view class="history-item" v-for="(item,index) in reverseHistoryList" :key="index">
					<uni-tag class="history-item-tag" :text="item" @click="gotoGoodsList(item)"/>
				</view>
			</view>	
			<view class="shop-list" v-else>
				<view class="shop-item" v-for="item in searchList" :key="item.goods_id" @click="gotoDetail(item.goods_id)">
					<text>{{item.goods_name}}</text>
					<uni-icons type="right" size="16"></uni-icons>	
				</view>
			</view>
		</view>		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				kw: "",
				// 该字段用来控制节流阀的开关时间
				timer: null,
				searchList: [],
				historyList: []
			};
		},
		computed: {
			reverseHistoryList () {
				// arr.reverse() 改变原数组
				return [...this.historyList].reverse();
			}
		},
		methods: {
			inputHandler(e) {	
				clearTimeout(this.timer);
				this.timer=setTimeout(()=> {
					this.kw=e;
					this.getSearchList();
					this.saveHistoryItem();
				},500)
			},
			async getSearchList() {
				let {data: res}= await uni.$http.get("/goods/qsearch",{query: this.kw})
				if(res.meta.status!==200) return uni.$showMsg();
				this.searchList=res.message
			},
			gotoDetail(id) {
				uni.navigateTo({
					url: "/subpkg/goods_detail/goods_detail?goods_id="+id
				})
			},
			saveHistoryItem() {
				let set=new Set(this.historyList)
				set.delete(this.kw)
				set.add(this.kw)
				this.historyList=Array.from(set)
				uni.setStorageSync("kw",JSON.stringify(this.historyList));
			},
			cleanHistory() {
				this.historyList=[];
				// 这里为了避免清除所有localStorage，不要使用uni.clearStorageSync
				uni.setStorageSync("kw",[]);			
			},
			gotoGoodsList(kw) {					
				uni.navigateTo({
					url: "/subpkg/goods_list/goods_list?query="+kw
				})
			}
		},
		mounted() {
			this.historyList=JSON.parse(uni.getStorageSync("kw")||"[]")
		}
	}
</script>

<style lang="scss">
.shop-list {
	padding: 0 5px;
	
	.shop-item {
		font-size: 12px;
		padding: 13px 0;
		border-bottom: 1px solid #efefef;
		display: flex;
		justify-content: space-between;
		align-items: center;
			
		text {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
}

.search-history {
	height: 40px;
	font-size: 13px;
	border-bottom: 1px solid #efefef;
	padding: 0 5px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.history-list {
	display: flex;
	flex-wrap: wrap;
	
	.history-item-tag {
		margin: 5px 5px 0 0;
	}
}
</style>
